package okhttp3.guide;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OkHttpLearn {

    public static void  main(String args[]) throws IOException {
        OkHttpClient client = new OkHttpClient();
        //getExample(client);
        MediaType JSON = MediaType.get("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(JSON,bowlingJson(
                "jesse"
                ,"jake"
        ));
        System.out.println("name ..."+Thread.currentThread().getName());
        Request request = new Request.Builder()
                .url("http://www.roundsapp.com/post")
                .post(body)
                .build();
        client.newCall(request)
                .enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {

                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {

                        System.out.println("thread name "+Thread.currentThread().getName()+"  call  "+response.body().string());
                    }
                });

    }

    private static void getExample(OkHttpClient client) throws IOException {
        Request request = new Request.Builder()
                .url("https://raw.github.com/square/okhttp/master/README.md")
                .build();
        Response response = client.newCall(request)
                .execute();
        System.out.println(response.body().string());
    }

  static   String  bowlingJson(String player1, String player2) {
        return "{'winCondition':'HIGH_SCORE',"
                + "'name':'Bowling',"
                + "'round':4,"
                + "'lastSaved':1367702411696,"
                + "'dateStarted':1367702378785,"
                + "'players':["
                + "{'name':'" + player1 + "','history':[10,8,6,7,8],'color':-13388315,'total':39},"
                + "{'name':'" + player2 + "','history':[6,10,5,10,10],'color':-48060,'total':41}"
                + "]}";
    }
}
